import React, { useEffect, useRef, useState } from 'react';
import { AlertResult, HttpCode } from '@/utils/contacts';
import { ConfigProvider, Modal, DatePicker, Form, Upload, Row, Col, message, Spin } from 'antd';
import styles from './index.less';
import TRNotification from '@/utils/notification';
import zhCN from 'antd/lib/locale/zh_CN';
import moment from 'moment';
import { updateFlair } from '@/services/user';

const ModalAlertComp = (props) => {
  const [visible, setVisible] = useState(true);
  const [loading, setLoading] = useState(false);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');
  const [leftFileList, setLeftFileList] = useState([]);
  const [rightFileList, setRightFileList] = useState([]);

  const formRef = useRef();
  const timeList = ['effectiveTime', 'reviewTime'];

  useEffect(() => {
    let initValue = props.initValue || {};
    timeList.forEach((n) => {
      if (initValue[n]) {
        initValue[n] = moment(initValue[n]);
      } else {
        initValue[n] == undefined;
      }
    });
    if (initValue.leftFileId) {
      setLeftFileList([
        {
          id: initValue.leftFileId,
          name: initValue.leftFileName,
          url: initValue.leftFilePath,
        },
      ]);
    }
    if (initValue.rightFileId) {
      setRightFileList([
        {
          id: initValue.rightFileId,
          name: initValue.rightFileName,
          url: initValue.rightFilePath,
        },
      ]);
    }
    formRef.current?.setFieldsValue?.({
      ...initValue,
    });
  }, []);
  const _onClose = (index) => {
    props.fn(index);
    setVisible(false);
  };

  const GetFileBase64 = (file) => {
    return new Promise((resolve, reject) => {
      const reader = new window.FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
    });
  };

  const handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await GetFileBase64(file.originFileObj);
    }
    setPreviewImage(file.url || file.preview);
    setPreviewOpen(true);
    setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1));
  };

  const onSubmit = async () => {
    await formRef.current?.validateFields();
    const { initValue, id, personId, title } = props;
    let data = formRef.current?.getFieldsValue();
    let files = {};

    let params = {
      ...initValue,
      ...data,
      personId: personId,
      flairCode: id,
      flairName: title,
    };
    timeList.forEach((n) => {
      if (moment.isMoment(data[n])) {
        params[n] = moment(data[n].format('YYYY-MM-DD')).valueOf?.();
      }
    });
    if (data.leftFileName.file) {
      let name = data.leftFileName.file.name;
      files[name] = data.leftFileName.file.originFileObj;
      params.leftFileName = name;
    }
    if (data.rightFileName.file) {
      let name = data.rightFileName.file.name;
      files[name] = data.rightFileName.file.originFileObj;
      params.rightFileName = name;
    }
    let pData = new FormData();
    pData.append('body', new Blob([JSON.stringify(params)], { type: 'application/json' }));
    Object.keys(files).forEach((key) => {
      pData.append('files', new Blob([files[key]], {}), key);
    });
    setLoading(true);
    let res = await updateFlair(pData);
    setLoading(false);
    if (res?.statusCode === HttpCode.SUCCESS) {
      _onClose(AlertResult.SUCCESS);
    } else {
      message.error(res?.message || '请求失败');
    }
  };

  const beforeUpload = (a) => {
    if (
      !['gif', 'jpg', 'jpeg', 'bmp', 'tiff', 'tif', 'png', 'svg'].includes(
        a.name.split('.').at(-1).toLowerCase(),
      )
    ) {
      message.error('请上传图片');
      return Upload.LIST_IGNORE;
    }
  };

  const customRequest = (o) => {
    o?.onSuccess();
  };

  return (
    <ConfigProvider locale={zhCN}>
      <Modal
        centered
        closable={false}
        visible={visible}
        onCancel={() => _onClose(AlertResult.CANCEL)}
        onOk={() => onSubmit()}
        width={600}
        maskClosable={false}
        okText="提交"
        cancelText="取消"
        //   okButtonProps={{ disabled: !inputValue.length }}
        className={styles.modalAlert}
        title={<div className={styles.title}>编辑</div>}
      >
        <Spin spinning={loading}>
          <Form ref={formRef} layout={'vertical'} wrapperCol={{ style: { width: '80%' } }}>
            <Row>
              <Col span={12}>
                <Form.Item
                  name={'reviewTime'}
                  reviewTime
                  label={'复审日期'}
                  rules={[{ required: true, message: '请选择复审日期' }]}
                >
                  <DatePicker placeholder="请选择复审日期" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name={'effectiveTime'}
                  label={'有效期'}
                  rules={[{ required: true, message: '请选择有效期' }]}
                >
                  <DatePicker placeholder="请选择有效期" />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item
                  name={'leftFileName'}
                  rules={[
                    { required: true, message: '请上传正面照' },
                    () => {
                      return {
                        validator: (rule, value) => {
                          if (value?.file?.status === 'removed') {
                            return Promise.reject('请上传正面照');
                          }
                          return Promise.resolve();
                        },
                      };
                    },
                  ]}
                  label={props.title || '高处作业证'}
                >
                  <Upload
                    fileList={leftFileList}
                    listType="picture-card"
                    onPreview={handlePreview}
                    onChange={({ fileList: newFileList }) => setLeftFileList(newFileList)}
                    beforeUpload={beforeUpload}
                    customRequest={customRequest}
                  >
                    {leftFileList.length >= 1 ? null : (
                      <div>
                        +
                        <div
                          style={{
                            marginTop: 8,
                          }}
                        >
                          正面
                        </div>
                      </div>
                    )}
                  </Upload>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item
                  name={'rightFileName'}
                  required={false}
                  rules={[
                    { required: true, message: '请上传反面照' },
                    () => {
                      return {
                        validator: (rule, value) => {
                          if (value?.file?.status === 'removed') {
                            return Promise.reject('请上传反面照');
                          }
                          return Promise.resolve();
                        },
                      };
                    },
                  ]}
                  label={' '}
                >
                  <Upload
                    fileList={rightFileList}
                    listType="picture-card"
                    onPreview={handlePreview}
                    onChange={({ fileList: newFileList }) => setRightFileList(newFileList)}
                    beforeUpload={beforeUpload}
                    customRequest={customRequest}
                  >
                    {rightFileList.length >= 1 ? null : (
                      <div>
                        +
                        <div
                          style={{
                            marginTop: 8,
                          }}
                        >
                          反面
                        </div>
                      </div>
                    )}
                  </Upload>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Spin>
      </Modal>
      <Modal
        visible={previewOpen}
        title={previewTitle}
        footer={null}
        onCancel={() => setPreviewOpen(false)}
        zIndex={1001}
      >
        <img
          alt="example"
          style={{
            width: '100%',
          }}
          src={previewImage}
        />
      </Modal>
    </ConfigProvider>
  );
};

class ModalAlert {
  __key__ = '';
  show = (props) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') {
        return;
      }
      const that = this;
      this.__key__ = String(Date.now());
      let fn = (index) => {
        that.__key__ = '';
        resolve({ index });
      };
      TRNotification.add({
        key: this.__key__,
        content: <ModalAlertComp fn={fn} {...props} />,
        duration: null,
      });
    });
  };
  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

const _ModalAlert = new ModalAlert();
export default _ModalAlert;
